package com.bp.hearthealth.pulse.lnapps.bp_utils

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import androidx.core.content.ContextCompat
import com.bp.hearthealth.pulse.lnapps.BpApplication
import java.lang.ref.WeakReference
import java.util.Stack

/**
 * 管理应用程序中所有Activity。
 *
 */
object BPActivityCollector {

    private val activitys = Stack<WeakReference<Activity>>()

    /**
     * 将Activity压入Application栈
     *
     * @param task 将要压入栈的Activity对象
     */
    fun pushTask(task: WeakReference<Activity>?) {
        activitys.push(task)
    }

    /**
     * 将传入的Activity对象从栈中移除
     *
     * @param task
     */
    fun removeTask(task: WeakReference<Activity>?) {
        activitys.remove(task)
    }

    /**
     * 根据指定位置从栈中移除Activity
     *
     * @param taskIndex Activity栈索引
     */
    fun removeTask(taskIndex: Int) {
        if (activitys.size > taskIndex) activitys.removeAt(taskIndex)
    }

    /**
     * 将栈中Activity移除至栈顶
     */
    fun removeToTop() {
        val end = activitys.size
        val start = 1
        for (i in end - 1 downTo start) {
            val mActivity = activitys[i].get()
            if (null != mActivity && !mActivity.isFinishing) {
                mActivity.finish()
            }
        }
    }

    /**
     * 移除全部（用于整个应用退出）
     */
    fun removeAll() {
        for (task in activitys) {
            val mActivity = task.get()
            if (null != mActivity && !mActivity.isFinishing) {
                mActivity.finish()
            }
        }
    }

    // 判断应用程序进程是否被杀死
    fun isAppProcessAlive(/*context: Context*/): Boolean {
        val am = BpApplication.context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningAppProcesses = am.runningAppProcesses
        if (runningAppProcesses != null) {
            for (processInfo in runningAppProcesses) {
                if (processInfo.processName == BpApplication.context.packageName) {
                    return true
                }
            }
        }
        return false
    }
    /**
     * 判断Activity是否Destroy
     * @param activityClass
     * @return true:已销毁
     */
    fun isActivityDestroy(activityClass: Class<*>): Boolean {
        val activityManager = ContextCompat.getSystemService(
            BpApplication.context,
            ActivityManager::class.java
        ) as ActivityManager

        val runningActivities = activityManager.getRunningTasks(Int.MAX_VALUE)
        for (taskInfo in runningActivities) {
            if (activityClass.name == taskInfo.baseActivity?.className) {
                return false
            }
        }
        return true
    }
}
